<?php

namespace App\Http\Controllers;

use DB;
use Storage;
use Hash;
use Laravel\Lumen\Routing\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Request AS UploadRequest;

class ApiController extends BaseController
{
    /**
     * Show the config.
     */
    public function config($table)
    {
        $result = $this::tableConfig($table);
        return $this::jsonResponse(false,$result);
    }


    /**
     * List the index.
     */
    public function index(Request $request,$table)
    {
        $data           = $request->all();
        $configResult   = $this::tableConfig($table);
        
        $filedStr   = ''; //字段过滤
        $relateStr  = ''; //表关联
        $filterStr  = ''; //内容过滤
        $orderStr   = ''; //排序规则
        //字段过滤 表关联
        foreach ($configResult['fields'] as $field) {
            $fieldName = $field['name'];
            if(!$field['is_hide']){
                $filedStr   .= "$table.$fieldName,";
            }
            $sameTableNum = 1;
            if(isset($field['relate']) && !isset($data['no_relate'])){
                $relateTable    = $field['relate']['table'];
                $relateField    = $field['relate']['field'];
                $relateSelect   = $field['relate']['select'];
                
                $relateTableOrigin = $relateTable;
                if($relateTable == $table){
                    $relateTable = $table.$sameTableNum++;
                }

                $filedStr   .= "$relateTable.$relateSelect AS ".$relateTableOrigin."_$relateSelect,";
                $relateStr  .= "LEFT JOIN $relateTableOrigin AS $relateTable ON $relateTable.$relateField = $table.$fieldName ";
            }
        }
        $filedStr  = substr($filedStr, 0, -1);

        //内容过滤
        if(isset($data['filter'])){
            foreach ($data['filter'] as $filter) {
                $filterField  = $filter[0];
                $filterSignal = $filter[1];
                $filterValue  = $filter[2];
                if($filterSignal == 'LIKE'){
                    $filterStr .= "$table.$filterField $filterSignal '%$filterValue%' AND ";
                }else{
                    $filterStr .= "$table.$filterField $filterSignal '$filterValue' AND ";
                }
            }
        }
        if(isset($data['filter_str'])){
            $filterStr .= $data['filter_str']." AND ";
        }
        $filterStr = $filterStr==''?'1':substr($filterStr, 0, -5);

        //分页
        $currentPage    = isset($data["currentPage"])?$data["currentPage"]:1;
        $countPerPage   = isset($data["countPerPage"])?$data["countPerPage"]:8;
        $countResult    = DB::select("select count(*) as count from $table where $filterStr");
        $count          = $countResult[0]->count;
        $lastPage       = ceil($count/$countPerPage);

        $result = [
            'countPerPage'  => $countPerPage,
            'count'         => $count,
            'lastPage'      => $lastPage,
            'currentPage'   => $currentPage
        ];
        $numStart       = $countPerPage*($currentPage-1);

        //排序规则
        if(isset($data['field'])){
            $field = $data['field'];
            $order = $data['order'] == 'true' ? 'DESC' : 'ASC';
            $orderStr .= " ORDER BY $field $order";
        }

        //执行
		$result['data'] = DB::select("

            SELECT $filedStr FROM $table
            $relateStr
            WHERE $filterStr
            $orderStr
            LIMIT $numStart,$countPerPage
            
        ");
       
        return $this::jsonResponse(false,$result);
    }


    /**
     * Show one object.
     */
    public function show($table,$id)
    {
        $result = DB::select("SELECT * FROM $table WHERE id=$id");
        return $this::jsonResponse(false,isset($result)?$result[0]:[]);
    }

    /**
     * Store one object.
     */
    public function store(Request $request,$table)
    {
        $data = $request->all();
        if(!$data){
            return $this::jsonResponse(true,'缺少重要参数');
        }
        
        //添加用户时，密码Hash处理
        if(isset($data['password'])){
            $data['password'] = Hash::make($data['password']);
        }
        $result = DB::table($table)->insertGetId($data);
        return $this::jsonResponse(false,$result);
    }

    /**
     * Update one object.
     */
    public function update(Request $request,$table,$id)
    {
        $data = $request->all();
        if(!$data){
            return $this::jsonResponse(true,'缺少重要参数');
        }
        //$result = DB::update('update $table set votes = 100 where id = $id';
        $result = DB::table($table)->where("id",$id)->update($data);
        return $this::jsonResponse(false,$result);
    }

    /**
     * Destroy one object.
     */
    public function destroy($table,$id)
    {

        $result = DB::delete("DELETE FROM $table WHERE id=$id");
        return $this::jsonResponse(false,$result);
    }


    /**
     * upload file.
     */
    public function upload(Request $request){
        if ($file = UploadRequest::file('file')) {
            $allowed_extensions = ["png", "jpg", "gif"];
            if ($file->getClientOriginalExtension() && in_array($file->getClientOriginalExtension(), $allowed_extensions)) {
                $folderName      = '/uploads/images/';
            }else{
                $folderName      = '/uploads/files/';
            }

            $client_name = $file->getClientOriginalName();         //获取客户端文件名
            $tmp_name    = $file->getFileName();                    //缓存在服务器端的文件名
            $extension   = $file->getClientOriginalExtension();     //上传文件的后缀
            $mimeTye     = $file->getMimeType();                    //获取文件类型
            $safename    = str_random(10).'.'.$extension;  
            $safeName        = date("Ymd", time()).str_random(10).'.'.$extension;

            $folderPath = $_SERVER["DOCUMENT_ROOT"].$folderName;
            $file->move($folderPath, $safeName);
            
            if(!file_exists($folderPath.$safeName)){
                return $this::jsonResponse(true,'上传失败');
            }else{
                return $this::jsonResponse(false,$folderName.$safeName,'上传成功');
            }
        } 
        
    }

}

